package com.shui_shui;

import com.shui_shui.compass.CompassView;
import com.shui_shui.compass.Degree;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.Display;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class CompassActivity extends Activity {
	
	private float[] aValues = new float[3];
	private float[] mValues = new float[3];
	private CompassView compassView;
	private SensorManager sensorManager;
	private int rotation;
	
	private int degree;
	
	private ImageView cb1;	
	private ImageView cb2;	
	private ImageView cb3;	
	private ImageView cb4;
	
	private TextView textcb1;
	private TextView textcb2;
	private TextView textcb3;
	
	private int degreeHomeRight = 0;
	private int degreeHomeCenter = 0;
	private int degreeHomeLift = 0;
	
	private Intent newActivity;
	
	private ImageView back;	
	private ImageView help; 
	
	/** Called when the activity is first created. */
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.compass);
    		
    		compassView = (CompassView)findViewById(R.id.compassView);
    		sensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
    		
    		String windoSrvc = Context.WINDOW_SERVICE;
    		WindowManager wm = ((WindowManager) getSystemService(windoSrvc));
    		Display display = wm.getDefaultDisplay();
    		rotation = display.getRotation();
    		
    		updateOrientation(new float[] {0, 0, 0});
    		
    		// Main Menu Image        
    		cb1 = (ImageView) findViewById(R.id.cb1);        
    		cb2 = (ImageView) findViewById(R.id.cb2);        
    		cb3 = (ImageView) findViewById(R.id.cb3);        
    		cb4 = (ImageView) findViewById(R.id.cb4);   
    		
    		textcb1 = (TextView) findViewById(R.id.textcb1);  
    		textcb2 = (TextView) findViewById(R.id.textcb2);  
    		textcb3 = (TextView) findViewById(R.id.textcb3);  
    		
    		// Menubar Image               
    		back = (ImageView) findViewById(R.id.back);        
    		help = (ImageView) findViewById(R.id.help);    
    		
    		cb1.setOnTouchListener(new OnTouchListener() {
	
				@SuppressWarnings("deprecation")
				public boolean onTouch(View v, MotionEvent event) {
					switch (event.getAction()) {            
					case MotionEvent.ACTION_DOWN:            
						cb1.setAlpha(150);                
						break;            
					case MotionEvent.ACTION_UP:            
						cb1.setAlpha(255);
						textcb1.setText(degree+"°");
						degreeHomeLift = degree;
						break;            
					default:                
						break;            
					}
					return true;
				}
			});
    		
    		cb2.setOnTouchListener(new OnTouchListener() {
    			
				@SuppressWarnings("deprecation")
				public boolean onTouch(View v, MotionEvent event) {
					switch (event.getAction()) {            
					case MotionEvent.ACTION_DOWN:            
						cb2.setAlpha(150);                
						break;            
					case MotionEvent.ACTION_UP:            
						cb2.setAlpha(255); 
						textcb2.setText(degree+"°");
						degreeHomeCenter = degree;
						break;            
					default:                
						break;            
					}
					return true;
				}
			});
    		
    		cb3.setOnTouchListener(new OnTouchListener() {
    			
				@SuppressWarnings("deprecation")
				public boolean onTouch(View v, MotionEvent event) {
					switch (event.getAction()) {            
					case MotionEvent.ACTION_DOWN:            
						cb3.setAlpha(150);                
						break;            
					case MotionEvent.ACTION_UP:            
						cb3.setAlpha(255);  
						textcb3.setText(degree+"°");
						degreeHomeRight = degree;
						break;            
					default:                
						break;            
					}
					return true;
				}
			});
    		
    		cb4.setOnTouchListener(new OnTouchListener() {
    			
				@SuppressWarnings("deprecation")
				public boolean onTouch(View v, MotionEvent event) {
					switch (event.getAction()) {            
					case MotionEvent.ACTION_DOWN:            
						cb4.setAlpha(150);                
						break;            
					case MotionEvent.ACTION_UP: 
						if(degreeHomeCenter!=0&&degreeHomeLift!=0&&degreeHomeRight!=0){
							Degree degreeHome = Degree.getDegree();
							degreeHome.setDegreeHomeCenter(degreeHomeCenter);
							degreeHome.setDegreeHomeLift(degreeHomeLift);
							degreeHome.setDegreeHomeRight(degreeHomeRight);
							newActivity = new Intent(CompassActivity.this,CalCompassActivity.class);
							cb4.setAlpha(255); 
							startActivity(newActivity);	
						}else{
							cb4.setAlpha(255);
							Toast.makeText(CompassActivity.this,"คุณยังกำหนดไม่ครบสามตำแหน่ง",Toast.LENGTH_LONG).show();
						}
						break;            
					default:                
						break;            
					}
					return true;
				}
			});
    		
    		back.setOnTouchListener(new OnTouchListener() {
    			
				@SuppressWarnings("deprecation")
				public boolean onTouch(View v, MotionEvent event) {
					switch (event.getAction()) {            
					case MotionEvent.ACTION_DOWN:            
						back.setAlpha(150);                
						break;            
					case MotionEvent.ACTION_UP:            
						back.setAlpha(255);	
						finish();
						break;            
					default:                
						break;            
					}
					return true;
				}
			});
    		
    		help.setOnTouchListener(new OnTouchListener() {
    			
				@SuppressWarnings("deprecation")
				public boolean onTouch(View v, MotionEvent event) {
					switch (event.getAction()) {            
					case MotionEvent.ACTION_DOWN:            
						help.setAlpha(150);                
						break;            
					case MotionEvent.ACTION_UP:            
						help.setAlpha(255);                
						break;            
					default:                
						break;                       
					}
					return true;
				}
			});
    		
    	
    }    
    
    private void updateOrientation(float[] values) {
    	if(0>values[0])
    		degree = (int)values[0]+360;
    	else if (0==values[0])
    		degree = 360;
    	else
    		degree = (int)values[0];
 
        if (compassView!= null&&values[0]!=0.0) {
        	compassView.setBearing(values[0]);
        	compassView.invalidate();
        }
    }
    
    private float[] calculateOrientation() {
    	float[] values = new float[3];
    	float[] inR = new float[9];
    	float[] outR = new float[9];
    	
    	// Determine the rotation matrix
    	SensorManager.getRotationMatrix(inR, null, aValues, mValues);
    	// Remap the coordinates based on the natural device orientation.
    	int x_axis = SensorManager.AXIS_X;
    	int y_axis = SensorManager.AXIS_Y;
    	
    	
    	switch (rotation) {
    		case (Surface.ROTATION_90):
    			x_axis = SensorManager.AXIS_Y;
    			y_axis = SensorManager.AXIS_MINUS_X;
    			break;
    		case (Surface.ROTATION_180):
    			y_axis = SensorManager.AXIS_MINUS_Y;
    			break;
    		case (Surface.ROTATION_270):
    			x_axis = SensorManager.AXIS_MINUS_Y;
    			y_axis = SensorManager.AXIS_X;
    			break;
    		default: break;
    	}
    	
    	SensorManager.remapCoordinateSystem(inR, x_axis, y_axis, outR);
    	
    	// Obtain the current, corrected orientation.
    	SensorManager.getOrientation(outR, values);
    	
    	// Convert from Radians to Degrees.
    	values[0] = (float) Math.toDegrees(values[0]);
    	values[1] = (float) Math.toDegrees(values[1]);
    	values[2] = (float) Math.toDegrees(values[2]);
    	return values;
    	
    	
    }
    private final SensorEventListener sensorEventListener = new SensorEventListener() {
    	public void onSensorChanged(SensorEvent event) {
    		if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
    			aValues = event.values;
    		if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD)
    			mValues = event.values;
    			updateOrientation(calculateOrientation());
    		}
    	public void onAccuracyChanged(Sensor sensor, int accuracy) {}
    };
    
    @Override
    protected void onResume() {
    	super.onResume();
    	Sensor accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    	Sensor magField = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
    	
    	sensorManager.registerListener(sensorEventListener,	accelerometer,SensorManager.SENSOR_DELAY_FASTEST);
    	sensorManager.registerListener(sensorEventListener,	magField, SensorManager.SENSOR_DELAY_FASTEST);
    }
    
    @Override
    protected void onPause() {
    	sensorManager.unregisterListener(sensorEventListener);
    	super.onPause();
    }
    
    @Override
    protected void onStop()
    {
    	sensorManager.unregisterListener(sensorEventListener);
    	super.onStop();
    }
}
